package com.dkd.quartz.task;

import com.dkd.common.constant.DkdContants;
import com.dkd.manage.service.*;
import com.dkd.manage.domain.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component("AutoReplenishment")
public class AutoReplenishment {
    private static final Logger log = LoggerFactory.getLogger(AutoReplenishment.class);

    @Autowired
    private IVendingMachineService vendingMachineService;

    @Autowired
    private IEmpService empService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private ITaskDetailsService taskDetailsService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private IJobService jobService;

    @Autowired
    private ISkuService skuService;

    private static final AtomicInteger counter = new AtomicInteger(0);


    @Transactional
    public void createAutoReplenishmentTasks() {
        log.info("开始执行自动补货任务创建");
        try {
            List<TaskDetails> taskDetailsList = new ArrayList<>(10);
            Job job = jobService.selectJobById(1L);
            if (job == null) {
                log.error("未找到ID为1的Job配置");
                return;
            }
            Long alertValue = job.getAlertValue();
            log.info("自动补货预警值：{}", alertValue);

            LocalDate today = LocalDate.now();
            String dateStr = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

            counter.set(0);

            VendingMachine vendingMachine = new VendingMachine();
            vendingMachine.setVmStatus(DkdContants.VM_STATUS_RUNNING);
            List<VendingMachine> machinesNeedingReplenishment = vendingMachineService.selectVendingMachineList(vendingMachine);
            if (machinesNeedingReplenishment.isEmpty()) {
                log.info("没有需要补货的设备");
                return;
            }

            for (VendingMachine vm : machinesNeedingReplenishment) {
                log.info("正在处理设备：{}", vm.getInnerCode());
                Emp emp = new Emp();
                emp.setRegionId(vm.getRegionId());
                emp.setRoleCode(DkdContants.ROLE_CODE_BUSINESS);
                emp.setStatus(DkdContants.EMP_STATUS_NORMAL);
                List<Emp> emps = empService.selectEmpList(emp);
                if (emps.isEmpty()) {
                    log.warn("设备 {} 所在区域没有可用的运营人员", vm.getInnerCode());
                    continue;
                }
                int index = (int) (Math.random() * emps.size());

                Task taskTest = new Task();
                taskTest.setInnerCode(vm.getInnerCode());
                taskTest.setProductTypeId(DkdContants.TASK_TYPE_SUPPLY);
                taskTest.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
                List<Task> taskList = taskService.selectTaskList(taskTest);
                taskTest.setTaskStatus(DkdContants.TASK_STATUS_PROGRESS);
                List<Task> taskList2 = taskService.selectTaskList(taskTest);
                if (taskList.isEmpty() && taskList2.isEmpty()) {
                    Task task = new Task();
                    task.setTaskCode(generateAutoTaskCode(dateStr));
                    task.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
                    task.setCreateType(0L);
                    task.setInnerCode(vm.getInnerCode());
                    task.setUserId(emps.get(index).getId());
                    task.setUserName(emps.get(index).getUserName());
                    task.setRegionId(vm.getRegionId());
                    task.setDesc("补货工单，该工单由系统自动创建");
                    task.setProductTypeId(DkdContants.TASK_TYPE_SUPPLY);
                    task.setAssignorId(0L);// 系统自动创建，没有指派人
                    task.setAddr(vm.getAddr());
                    taskService.insertTask(task);
                    log.info("为设备 {} 创建了新的补货工单", vm.getInnerCode());

                    Channel channelTest = new Channel();
                    channelTest.setVmId(vm.getId());
                    List<Channel> channels = channelService.selectChannelList(channelTest);
                    for (Channel channel : channels) {
                        if (channel == null) {
                            log.warn("发现空货道信息，跳过处理");
                            continue;
                        }
                        log.debug("处理货道: {}, 当前容量: {}, 最大容量: {}", channel.getChannelCode(), channel.getCurrentCapacity(), channel.getMaxCapacity());

                        if (channel.getCurrentCapacity() == null || channel.getMaxCapacity() == null || alertValue == null) {
                            log.warn("货道 {} 的容量信息或警戒值为空，跳过处理", channel.getChannelCode());
                            continue;
                        }

                        if (channel.getCurrentCapacity()*100 <= channel.getMaxCapacity() * alertValue) {
                            TaskDetails taskDetails = new TaskDetails();
                            taskDetails.setTaskId(task.getTaskId());
                            taskDetails.setChannelCode(channel.getChannelCode());
                            taskDetails.setExpectCapacity(channel.getMaxCapacity() - channel.getCurrentCapacity());

                            Long skuId = channel.getSkuId();
                            if (skuId == null) {
                                log.warn("货道 {} 没有关联的SKU，跳过处理", channel.getChannelCode());
                                continue;
                            }
                            taskDetails.setSkuId(skuId);

                            Sku sku = skuService.selectSkuBySkuId(skuId);
                            if (sku == null) {
                                log.warn("未找到SKU信息，SKU ID: {}", skuId);
                                continue;
                            }
                            taskDetails.setSkuName(sku.getSkuName());
                            taskDetails.setSkuImage(sku.getSkuImage());

                            taskDetailsList.add(taskDetails);
                            log.info("为货道 {} 创建了补货详情，预期补货数量: {}", channel.getChannelCode(), taskDetails.getExpectCapacity());
                        }
                    }
                } else {
                    log.info("设备 {} 已有待办或进行中的补货工单，跳过创建", vm.getInnerCode());
                }
            }

            if (!taskDetailsList.isEmpty()) {
                taskDetailsService.batchInsertTaskDetails(taskDetailsList);
                log.info("批量插入了 {} 条工单详情", taskDetailsList.size());
            } else {
                log.info("没有需要插入的工单详情");
            }
            log.info("自动补货任务创建完成，共创建 {} 个工单详情", taskDetailsList.size());
        } catch (Exception e) {
            log.error("自动补货任务创建过程中发生错误", e);
            throw e; // 重新抛出异常，以确保事务回滚
        }
    }

    private String generateAutoTaskCode(String dateStr) {
        int count = counter.getAndIncrement();
        char letter = (char) ('A' + (count / 999));
        int number = count % 999 + 1;
        return String.format("%s%c%03d", dateStr, letter, number);
    }
}